// 运行时配置

import { currentUrl, pre } from '@/env/env';
import '@/utils/autoUpdate';
import { RequestConfig, RunTimeLayoutConfig, history } from '@umijs/max';
import { Avatar, Dropdown } from 'antd';
import Footer from './components/Footer/Footer';
import Empty from './pages/404';
import AccessNo from './pages/accessNo';

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<{
  name: string;
  avatar: string;
  isCanReadPageA: boolean;
}> {
  return {
    name: '成爸爸',
    avatar: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    isCanReadPageA: false,
  };
}
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    menu: {
      locale: false,
    },
    rightContentRender: false,
    footerRender: () => <Footer />,
    logout: () => {
      return Promise.resolve();
    },
    noFound: <Empty />,
    unAccessible: <AccessNo />,
    layout: 'mix',
    token: {
      sider: {
        colorMenuBackground: '#fff',

        colorMenuItemDivider: 'rgba(255,255,255,0.15)',
        colorBgMenuItemHover: '#e6f4ff',
        colorBgMenuItemSelected: '#e6f4ff',
        colorTextMenuSelected: '#1677ff',
        colorTextMenuItemHover: '#1677ff',
        colorTextMenuTitle: 'rgba(255,255,255,0.95)',
        colorTextMenuActive: '#1677ff',
        colorTextSubMenuSelected: '#1677ff',
      },
    },
    avatarProps: {
      render: () => {
        const logout = () => {
          localStorage.clear();
          sessionStorage.clear();
          history.push('/login');
        };
        const items = [
          {
            key: '1',
            label: <div onClick={logout}>退出登录</div>,
          },
        ];
        return (
          <div>
            <Dropdown menu={{ items }}>
              <div>
                <Avatar src={initialState.avatar}></Avatar>
                <span style={{ marginLeft: '10px' }}>{initialState.name}</span>
              </div>
            </Dropdown>
          </div>
        );
      },
    },
  };
};

// 与后端约定的响应数据格式
interface ResponseStructure {
  code: string;
  data: any;
  message: string;
}
export const request: RequestConfig = {
  timeout: 1000,
  baseURL: currentUrl + pre,
  // other axios options you want
  errorConfig: {
    errorThrower(res: ResponseStructure) {
      // const { code, message, data } = res;
    },
    errorHandler() {},
  },
  requestInterceptors: [
    (config) => {
      // 设置token
      const token = 123;
      if (token) {
        config.headers.Authorization = `${token}`;
      }
      // 拦截请求配置，进行个性化处理。
      const url = config.url;
      return { ...config, url };
    },
  ],
  responseInterceptors: [
    (response) => {
      console.log('response', response);

      // 拦截响应数据，进行个性化处理
      return response;
    },
  ],
};
